#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "DuLink.h"  


void file_read(char *path, DuLinkList *L)
{
    FILE *file = fopen(path, "r");
    if (!file) 
    {
        fprintf(stderr, "Failed to open file: %s\n", path);
        return;
    }
   
    
    char arr[1024];
    char *str = NULL;
    //获取链表的长度
    int length = 0;
    DuLinkList p = (*L)->next;  
    while (p != NULL) 
    {
        length++;
        p = p->next;
    }
    
    int lineNumber = 1;
    while ((str = fgets(arr, sizeof(arr), file)) != NULL) 
    {
        if (str[strlen(str) - 1] == '\n') 
        {
            str[strlen(str) - 1] = '\0';
        }
        
        Insert_DL(L, length + lineNumber, str);
        lineNumber++;
    }
   
    fclose(file);
}
void file_append(char *path,  DuLinkList *L)
{
    FILE *file = fopen(path, "a");
    if (!file) 
    {
        fprintf(stderr, "Failed to open file: %s\n", path);
        return;
    }

    DuLinkList p = *L;
    while(p)
    {
        fputs(p->info, file);
        fputc('\n', file);
        p=p->next;
    }
    
    fclose(file);
    printf("Successfully appended to file: %s\n", path);
}
void file_write(char *path, char *str)
{
    FILE *file = fopen(path, "w");
    if (!file) 
    {
        fprintf(stderr, "Failed to open file: %s\n", path);
        return;
    }
    
    fputs(str, file);
    
    fclose(file);
    printf("Successfully wrote to file: %s\n", path);
}
